package com.yinp.showview.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import androidx.annotation.ColorRes;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.yinp.showview.R;

public class ColorCircleLinearLayout extends LinearLayout {
    public ColorCircleLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ColorCircleLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private Paint circlePaint;
    private int radius;

    private void init(Context context, @Nullable AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ColorCircleLinearLayout);

        int bgColor = ta.getColor(R.styleable.ColorCircleLinearLayout_ccll_bgColor, 0);

        ta.recycle();

        setBackground(null);
        circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        circlePaint.setColor(bgColor);
        circlePaint.setStyle(Paint.Style.FILL);

        setWillNotDraw(false);
    }

    private boolean isFirst = true;

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (isFirst) {
            isFirst = false;
            int height = getHeight();
            int width = getWidth();
            if (height > width) {
                radius = width / 2;
            } else {
                radius = height / 2;
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(radius, radius, radius, circlePaint);
    }

    /**
     * 动态改变颜色
     *
     * @param color
     */
    public void changeColor(int color) {
        circlePaint.setColor(color);
        postInvalidate();
    }

    public void changeColor(Context context, @ColorRes int color) {
        circlePaint.setColor(ContextCompat.getColor(context, color));
        postInvalidate();
    }
}
